package fafu.comedu.workerrepair.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import fafu.comedu.workerrepair.R;
import fafu.comedu.workerrepair.command.Dictionary;
import fafu.comedu.workerrepair.command.LocalDataStream;
import fafu.comedu.workerrepair.command.ReJsonRsp;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HumanInfoChange extends Fragment {
    private TextView infoName;
    private TextView infoPhone;
    private EditText infoMsg;
    private Button infoSubmit;
    private static int RENDER = 1;
    private static int showToast = 4;
    private static int dismissPD = 6;
    private ProgressDialog pd;
    private ReJsonRsp humanInfo;
    private String name;
    private String type;
    private String pdTitle;
    private String pdMsg;
    private String toastMsg;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == RENDER)
                dataRender();
            else if(msg.what == showToast)
                showToast();
            else if(msg.what == dismissPD)
                dismissPD();
        }
    };


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    private  void showPD(){
        pd= ProgressDialog.show(getActivity(), pdTitle, pdMsg);
    }
    private  void showPD(String pdTitle,String pdMsg){
        pd= ProgressDialog.show(getActivity(), pdTitle, pdMsg);
    }
    private void showToast(){
        Toast toast = Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG);
        toast.show();
    }
    private void dismissPD(){
        pd.dismiss();
    }
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.human_info_change,container,false);
        infoName = view.findViewById(R.id.info_name);
        infoPhone = view.findViewById(R.id.info_phone);
        infoMsg = view.findViewById(R.id.info_msg);
        infoSubmit = view.findViewById(R.id.info_submit);
        infoSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPD("修改提交","数据提交中…");
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        String idenAndpwd = "";
                        try {//判断是否已经登陆
                            idenAndpwd = LocalDataStream.read(getActivity().openFileInput("data"));
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        if(idenAndpwd.equals("")){
                            Toast toast = Toast.makeText(getActivity(),"非法使用",Toast.LENGTH_LONG);
                            toast.show();
                            return ;
                        }
                        /**
                         * 开始从后端取值
                         */
                        String iden = idenAndpwd.split("_")[0];
                        String msg = infoMsg.getText().toString();
                        Log.i("changmsg", "run: "+msg);
                        Log.i("changmsg", "run: "+Dictionary.url.head+"appwork/msgchange?workerId="+iden+"&msg="+msg);
                        final Request request = new Request.Builder()
                                .url(Dictionary.url.head+"appwork/msgchange?workerId="+iden+"&msg="+msg)
                                .get()
                                .build();
                        OkHttpClient okHttpClient = new OkHttpClient();
                        Response response = null;
                        try {
                            response = okHttpClient.newCall(request).execute();
                            String json = response.body().string();
                            ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                            Integer code = reJsonRsp.getCode();
                            Log.i("chang msg", "run: "+json);
                            if(code.equals(0)){
                                toastMsg = "修改成功";
                                Message message = new Message();
                                message.what = showToast;
                                handler.sendMessage(message);
                            }else{
                                toastMsg = reJsonRsp.getMsg();
                                Message message = new Message();
                                message.what = showToast;
                                handler.sendMessage(message);
                            }
                            Message message = new Message();
                            message.what = dismissPD;
                            handler.sendMessage(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                };
                Thread thread = new Thread(runnable);
                thread.start();
            }
        });
        initData();
        return view;
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden)  return;//隐藏页面，不操作
        initData();
    }
    private void initData() {
        String idenAndpwd = "";
        try {//判断是否已经登陆
            idenAndpwd = LocalDataStream.read(getActivity().openFileInput("data"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(idenAndpwd.equals("")){
            Toast toast = Toast.makeText(getActivity(),"非法使用",Toast.LENGTH_LONG);
            toast.show();
            return ;
        }
        /**
         * 开始从后端取值
         */
        String iden = idenAndpwd.split("_")[0];
        OkHttpClient okHttpClient = new OkHttpClient();
        String clientUrl = Dictionary.url.head + "appwork/getInfo?id="+iden;
        Log.i("humaninfo", "initRecordList: "+clientUrl);
        final Request request = new Request.Builder()
                .url(clientUrl)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        pd= ProgressDialog.show(getActivity(), "获取信息", "获取信息中…");
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i(name+"Record", "onFailure: "+e);
                pd.dismiss();
                Toast toast = Toast.makeText(getActivity(),"数据请求异常",Toast.LENGTH_LONG);
                toast.show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.i(name+"Record", "onResponse: " + json);
                ReJsonRsp reJsonRsp = JSONObject.parseObject(json,new TypeReference<ReJsonRsp>(){});
                humanInfo = reJsonRsp;//渲染list
                Message message = new Message();
                message.what=RENDER;
                handler.sendMessage(message);
                pd.dismiss();
            }
        });

    }

    private void dataRender() {
        JSONObject data = (JSONObject) humanInfo.getData();
        infoName.setText(data.getString("name"));
        infoPhone.setText(data.getString("phone"));
        infoMsg.setText(data.getString("work"));
    }



}
